/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.yangying.androidframework.core.adapter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import net.yangying.androidframework.R;
import net.yangying.androidframework.core.model.GalleryImage;
import net.yangying.androidframework.util.Constant;
import net.yangying.androidframework.util.FileUtil;
import net.yangying.androidframework.util.MD5Utils;
import net.yangying.androidframework.util.RemoteResourceManager;
import net.yangying.androidframework.util.SDCardUtil;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

public class HomeMainPictureAdapter extends BaseGroupAdapter<GalleryImage> implements ObservableAdapter {

	private static final String TAG = HomeMainPictureAdapter.class.getSimpleName();

    private RemoteResourceManager mRrm;
    private RemoteResourceManagerObserver mResourcesObserver;
    private Handler mHandler = new Handler();

    private Set<String> mLaunchedPhotoFetches;

    int mGalleryItemBackground;
    private Context mContext;
    private HashMap<String,Bitmap> map;
    
    Bitmap bmp_default=null;
//    Bitmap bmp_default_corner=null;
    
    private int select=0;

    
    public HomeMainPictureAdapter(Context context, RemoteResourceManager rrm)
    {
        super(context);
        this.mContext=context;
        mRrm = rrm;
        mResourcesObserver = new RemoteResourceManagerObserver();
        mLaunchedPhotoFetches = new HashSet<String>();
        map = new HashMap<String,Bitmap>();
        mRrm.addObserver(mResourcesObserver);
        bmp_default=BitmapFactory.decodeResource(mContext.getResources(), R.drawable.mainpicture_default); 
//        bmp_default_corner=BitmapUtils.getRCB(bmp_default, 8);
    }

    public HomeMainPictureAdapter(Context context, int layoutResource) {
        super(context);
        this.mContext=context;
    }
    
    
    @Override
    public int getCount() {
//        return (group == null) ? 0 : Integer.MAX_VALUE; //无线循环
        return (group == null) ? 0 : group.size();
    }
    
    @Override
    public Object getItem(int position) {
        return group.get(position%this.getGroup().size());
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public LinearLayout getImageView(Bitmap bitmap,String text,int postion)
    {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.gallery_image_item, null);
        ImageView imageView = (ImageView)layout.findViewById(R.id.gallery_image_item_imageview);
        imageView.setImageBitmap(bitmap);
        imageView.setScaleType(ScaleType.FIT_XY);
        return layout;
    }

    public void setSeleted(int pos) {
            select = pos;
            super.notifyDataSetChanged();
       }

    public View getView(int position, View convertView, ViewGroup parent) {
//        return mImages[position];
//        if(DEBUG)Log.d(TAG, "getView"+position);
        
    	//无限循环
//        if(position<0){
//            position =position+this.getGroup().size();
//          }
//
//        int pos=0;
//        pos=position%this.getGroup().size();

        
        GalleryImage mainPicture = (GalleryImage) getItem(position);
        
        ViewHolder holder; 

        if (convertView == null) {
            holder = new ViewHolder();
            convertView=getImageView(bmp_default,mainPicture.getImage(),position);
            holder.mainpictureImageView =  (LinearLayout)convertView;
            convertView.setTag(holder); 
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        ImageView imageview=(ImageView)(ImageView)holder.mainpictureImageView.findViewById(R.id.gallery_image_item_imageview);

        Uri photoUri = null;
        if(mainPicture.getImage()!=null)
        {
        	String imgurlmd5 = MD5Utils.md5(mainPicture.getImage());
            if(!map.containsKey(imgurlmd5))
            {
            	if(mainPicture.getImage().startsWith(Constant.SCHEME_HTTP)
            			||mainPicture.getImage().startsWith(Constant.SCHEME_HTTPS)){
                    try {
                        photoUri = Uri.parse(mainPicture.getImage());
                        InputStream is=mRrm.getInputStream(photoUri);
                        Bitmap bitmap=null;
//                        Bitmap bitmap_corner=null;
                        if(is!=null){
                            bitmap = BitmapFactory.decodeStream(is);
                            if(bitmap!=null){
//                                bitmap_corner=BitmapUtils.getRCB(bitmap, 8);
                                imageview.setImageBitmap(bitmap);
                                if(!map.containsKey(imgurlmd5))
                                    map.put(imgurlmd5, bitmap);
                            }
                            else{
                                imageview.setImageBitmap(bmp_default);
                            }
                        }
                        else {
                            imageview.setImageBitmap(bmp_default);
                        }
                    } catch (IOException e) {
                        imageview.setImageBitmap(bmp_default);
                        if (!mLaunchedPhotoFetches.contains(imgurlmd5)) {
                            mLaunchedPhotoFetches.add(imgurlmd5);
                            mRrm.request(photoUri);
                        }
                    } catch(Exception e)
                    {
                        imageview.setImageBitmap(bmp_default);
                    }            		
            	} else if (mainPicture.getImage().startsWith("images/")){
                  InputStream is=FileUtil.readFileInputStream(SDCardUtil.getCachePathPrefix()+ File.separator + mainPicture.getImage());
                  Bitmap bitmap=null;
//                  Bitmap bitmap_corner=null;
                  if(is!=null){
                      bitmap = BitmapFactory.decodeStream(is);
                      if(bitmap!=null){
//                          bitmap_corner=BitmapUtils.getRCB(bitmap, 8);
                          imageview.setImageBitmap(bitmap);
                          if(!map.containsKey(imgurlmd5))
                              map.put(imgurlmd5, bitmap);
                      }
                      else{
                          imageview.setImageBitmap(bmp_default);
                      }
                      try {
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                  } else {
                      imageview.setImageBitmap(bmp_default);
                  }
            		
            	}

            }else{
                Bitmap bitmap=null;
                bitmap=map.get(imgurlmd5);
                if(bitmap!=null){
                    imageview.setImageBitmap(bitmap);
                }
                else{
                    imageview.setImageBitmap(bmp_default);
                }
            }
        }else
            {
            imageview.setImageBitmap(bmp_default);
            }
        return convertView;
    }

    public float getScale(boolean focused, int offset) {
        return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
    }

    @Override
    public void removeObserver() {
        mHandler.removeCallbacks(mUpdatePhoto);
        mRrm.deleteObserver(mResourcesObserver);
    }

    private class RemoteResourceManagerObserver implements Observer {
        @Override
        public void update(Observable observable, Object data) {
            mHandler.post(mUpdatePhoto);
        }
    }

    private Runnable mUpdatePhoto = new Runnable() {
        @Override
        public void run() {
            notifyDataSetChanged();
        }
    };

    static class ViewHolder {
        public LinearLayout mainpictureImageView;
    }
}
